#!/bin/bash
# Copyright 2025 Supabase, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Get list of staged files that need license headers
staged_files=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(go|sh|proto)$')
if [ -z "$staged_files" ]; then
  exit 0
fi

# Check for Go files with multi-line license comments (/* */) - these should be single-line (//)
files_with_multiline_license=()

# Check if files have proper license headers
files_without_license=()

for file in $staged_files; do
  # Skip files in excluded directories
  if [[ "$file" == site/* ]] || [[ "$file" == pb/* ]] || [[ "$file" == dist/* ]] || [[ "$file" == bin/* ]]; then
    continue
  fi

  # Check for multi-line license comments in Go files
  if [[ "$file" == *.go ]] && [[ -f "$file" ]] && head -1 "$file" | grep -q '^/\*'; then
    files_with_multiline_license+=("$file")
  fi

  # Check if file exists and has license header
  if [[ -f "$file" ]] && ! head -20 "$file" | grep -q "Copyright.*Supabase, Inc\."; then
    files_without_license+=("$file")
  fi
done

# Reject commit if Go files have multi-line license comments
if [ ${#files_with_multiline_license[@]} -ne 0 ]; then
  echo "Go files with multi-line license comments found!"
  echo ""
  echo "The following files use /* */ license comments instead of // comments:"
  printf '  %s\n' "${files_with_multiline_license[@]}"
  echo ""
  echo "Please convert these files to use single-line license comments (//)."
  echo "Change the multi-line format from:"
  echo "  /*"
  echo "  Copyright ..."
  echo "  */"
  echo "to single-line format:"
  echo "  // Copyright ..."
  echo ""
  exit 1
fi

# Check if addlicense is installed
if ! command -v addlicense >/dev/null 2>&1; then
  echo "addlicense not found. Please install it by running 'make tools'"
  exit 1
fi

if [ ${#files_without_license[@]} -ne 0 ]; then
  echo "Adding license headers to files missing them:"
  printf '%s\n' "${files_without_license[@]}"
  echo ""

  # Add license headers to the specific files
  for file in "${files_without_license[@]}"; do
    echo "Adding license to: $file"
    addlicense -c "Supabase, Inc." -l apache "$file"
    # Stage the modified file so it's included in this commit
    git add "$file"
  done

  echo "License headers added and staged successfully"
fi
